package cn.y.operation.framework.utils.dev;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName: CollectionUtiles
 * @author: 叶子豪
 * @create: 2020-11-02 21:12
 */
public class CollectionUtils {
    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static <K extends Comparable<? super K>, V> Map<K, V> sortMapByKey(Map<K, V> map) {
        Map<K, V> result = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Map.Entry.<K, V>comparingByKey()
                        .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        return result;
    }
    /*public static Map<Object, Object> sortMapByKey(Map<String, String> map) {
        Map<Object, Object> resultMap = new HashMap<>();
        Set set = map.keySet();
        Object[] arr = set.toArray();
        Arrays.sort(arr);
        for (Object key : arr) {
            //System.out.println(key + ": " + map.get(key));
            resultMap.put(key, map.get(key));
        }
        return resultMap;
    }*/

    /**
     * 获取map中第一个key值
     *
     * @param map 数据源
     * @return
     */
    public static String getKeyOrNull(Map<String, Object> map) {
        String obj = null;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            obj = entry.getKey();
            if (obj != null) {
                break;
            }
        }
        return obj;
    }


    /**
     * 获取map中第一个数据值
     *
     * @param map 数据源
     * @return
     */
    public static String getFirstOrNull(Map<String, String> map) {
        String obj = null;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            obj = entry.getValue();
            if (obj != null) {
                break;
            }
        }
        return obj;
    }
}
